<?php

namespace app\admin\model;
use think\Db;
use think\exception\PDOException;
use think\Model;

class CepingModel extends Model
{
    protected $name = 'ceping';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function questionCat()
    {
        return $this->belongsTo('QuestionCat','cat_id')->field('name as c_name');
    }


    public function upQuestion($type)
    {
        $a = $type == 1 ? 1 : -1;
        $b = $type == 1 ? -1 : 1;
        $this->where('is_show',$b)->update(['is_show'=>$a]);
        return ['code' => 1, 'data' => '', 'msg' => '下架成功'];
    }

    /**
     * 根据搜索条件获取轮播列表信息
     */
    public function getDataByWhere($map, $Nowpage, $limits)
    {
        return $this->alias('q')->field('q.*,c.name as c_name')->join('think_ceping_cat c', 'q.cat_id = c.id','left')->where($map)->page($Nowpage, $limits)->order('sort asc')->select();
    }


    /**
     * params $param
     * @author felix
     */
    public function insertData($param)
    {
        try{
            $result = $this->validate('QuestionValidate')->allowField(true)->save($param);
            if(false === $result){
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
                //计算商品的星星
                return ['code' => 1, 'data' => '', 'msg' => '添加成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }



    /**
     * @author felix
     */
    public function updateData($param)
    {
        try{
            $result = $this->allowField(true)->save($param, ['id' => $param['id']]);
            if(false === $result){
                return ['code' => 0, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑成功'];
            }
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }



    /**
     * @author felix
     */
    public function getOneData($id)
    {
        return $this->where('id', $id)->find();
    }



    /**
     * @author felix
     */
    public function delData($id)
    {
        try{
            $this->where('id', $id)->delete();
            return ['code' => 1, 'data' => '', 'msg' => '删除成功'];
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }


}